/*
 * ProgressInputStream.java
 *
 * Copyright(c) 2010
 * Michael Kroez
 * kroez@studiorutton.de
 *
 * All rights reserved.
 *
 * $Id$
 * 
 */

package de.studiorutton.access;

import java.io.IOException;
import java.io.InputStream;

import android.util.Log;

public class ProgressInputStream extends InputStream {
	private final static String TAG = "progressinputstream";

	private final InputStream in;
	private final long contentLength;
	private long currentContentLength;
	private IProgressListener pl = null;
	private long modulo;

	ProgressInputStream(InputStream in, long contentLength) {
		this.in = in;
		this.contentLength = contentLength;
		modulo = contentLength / 100;
//		Log.d(TAG, "ProgressInputStream: modulo = " + modulo );
	}

	public void setProgressListener(IProgressListener pl) {
		this.pl = pl;
	}

	public long getCurrentContentLength() {
		return currentContentLength;
	}

	@Override
	public int read() throws IOException {
		
		int b = in.read();
		if (b > 0) {
			currentContentLength++;
			if (pl != null) {
//				Log.d( TAG, "ProgressInputStream: notifying( " + currentContentLength + ", " + contentLength + ")");
				if (currentContentLength % modulo ==  0) {
//					Log.d(TAG, "ProgressInputStream: notifyProgress(" + calculateProgress() + ", " + currentContentLength + ", " + contentLength + ")");
					pl.notifyProgresss(calculateProgress(), currentContentLength, contentLength);
				}
				else if ((contentLength - currentContentLength) <= modulo) {
					modulo = modulo / 2;
//					Log.d(TAG, "ProgressInputStream: notifyProgress - full 100% ( " + calculateProgress() + ", " + currentContentLength + ", " + contentLength + ")");
					pl.notifyProgresss( calculateProgress(), contentLength, contentLength );						
				}
			}
		}

		return b;
	}

	public int calculateProgress() {
		return (int) ((currentContentLength * 10000) / contentLength);
	}

}
